<template>
  <div class="suggest-container">
    <van-cell-group>
      <van-cell
        @click="$emit('search',item)"
        v-for="(item, index) in suggestData"
        :key="index"
        icon="location-o"
      >
        <div class="title" slot="title" v-html="lightColor(item)"></div>
      </van-cell>
    </van-cell-group>
  </div>
</template>

<script>
import { debounce } from "lodash";
import { getSearchSuggestionsApi } from "@/api";

export default {
  props: ["value"],
  name: "",
  data() {
    return {
      suggestData: []
    };
  },
  methods: {
    //  获取搜索建议
    // getSuggetsData2:function(){},
    async getSuggetsData() {
      // debounce(function(){
      // },300)

      const { data: res } = await getSearchSuggestionsApi(this.value);
      console.log(res, 55566677);
      this.suggestData = res.data.options;
    },

    //  实现 搜索关键字高亮显示
    lightColor(str) {
      //var  str='123abc123Abc'
      /* 
        目的：将里面的所有的a  变成===666===      123===666===bc123Abc
        */
      //new  RegExp(将要替换的值,全局替换【不区分大小写】)

      var reg = new RegExp(this.value, "gi");
      // str.replace(规则,将要替换的值)
      return str.replace(reg, `<span style="color:red">${this.value}</span>`);
    },

    // qqq(){
    //   this.$emit('search')
    // }
  },
  watch: {
    // value(){
    //   console.log(111111);
    // }
    value: {
      // handler:function(newVal,olgVal){
      //   console.log(newVal,olgVal,44444);
      //   //  只要这个值发生了改变
      // console.log(this.value,55555);
      // },
      // immediate:true  //  值只要发生改变就立刻执行回调
      handler: debounce(function(newVal, olgVal) {
        if (!newVal.length) {
          return;
        }
        this.getSuggetsData();
      }, 300),
      immediate: true //  值只要发生改变就立刻执行回调
    }
  }
};
</script>
<style lang="less" scoped></style>
